{$ifdef interface}
type
  TAppQueryTab = class
    public
      sql: string;
      grid : TAppDataGrid;
      memo : TAppMemo;
      sheet: TTabSheet;
      constructor Create(AOwner:TPageControl);
      procedure loadGrid;
    private
      procedure onKeyDown(Sender: TObject; var Key: word; Shift: TShiftState);
  end;

  TAppQueryTabs = class
    public
      var parent:TPageControl;
      constructor Create;
      function Add:TTabSheet;
      procedure Remove(index:word);

    private
      query : array of TAppQueryTab;
  end;

var queries: TAppQueryTabs;
{$endif}

{$ifdef implementation}

constructor TAppQueryTab.Create(AOwner:TPageControl);
begin
  inherited Create;
  sheet := TTabSheet.Create(AOwner);
  sheet.Caption:='Query ';
  sheet.Parent:=AOwner;
  sheet.PageControl:=AOwner;

  self.grid:=TAppDataGrid.Create(nil);
  self.grid.Parent:=sheet;
  self.grid.Align:=alClient;

  self.memo:=TAppMemo.Create(nil);
  self.memo.Parent:=sheet;
  self.memo.Align:=alTop;
  self.memo.Highlighter.CommentAttribute.Foreground:=_config.data.getObjectFor('editor_comment_color',EDITOR_COMMENT_COLOR_DEFAULT).asInt;
  self.memo.Highlighter.IdentifierAttribute.Foreground:=_config.data.getObjectFor('editor_identifier_color',EDITOR_IDENTIFIER_COLOR_DEFAULT).asInt;
  self.memo.Highlighter.KeywordAttribute.Foreground:=_config.data.getObjectFor('editor_keyword_color',EDITOR_KEYWORD_COLOR_DEFAULT).asInt;
  self.memo.Highlighter.StringAttribute.Foreground:=_config.data.getObjectFor('editor_string_color',EDITOR_STRING_COLOR_DEFAULT).asInt;
  self.memo.Text:='select * from information_schema.tables as t';
  self.memo.OnKeyDown:=@self.onKeyDown;
  self.sql := '';
end;

procedure TAppQueryTab.onKeyDown(Sender: TObject; var Key: word; Shift: TShiftState);
begin
  if (key = $78 {F9}) then
  begin
    with sender as TAppMemo do
    begin
      _db.db.loadDataFromSQL(Text,self.grid)
    end;
  end;

end;

procedure TAppQueryTab.loadGrid;
begin
  db.loadDataFromSQL(self.sql,self.grid);
end;

// //
constructor TAppQueryTabs.Create;
begin
  setLength(query,0);
end;

function TAppQueryTabs.Add:TTabSheet;
begin
  setLength(query,length(query)+1);
  query[length(query)-1] := TAppQueryTab.Create(self.parent);
  result := query[length(query)-1].sheet;
  //
end;

procedure TAppQueryTabs.Remove(index:word);
begin
  if (length(query) > 0) then
  begin
    query[index] := query[length(query)-1];
    setLength(query,length(query)-1);
  end;
  //
end;


{$endif}

{$ifdef initialization}
  queries := TAppQueryTabs.Create;
{$endif}
